#include "List.h"

LTNode* CreateLTNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	newnode->prev = NULL;
	newnode->next = NULL;
	newnode->data = x;
	return newnode;
}

LTNode* LTNodeInit()
{
	LTNode* phead = CreateLTNode(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void LTDestory(LTNode* plist)
{
	assert(plist);
	LTNode* cur = plist->next;
	while (cur != plist)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}

	free(plist);
	plist = NULL;
}

void LTPrint(LTNode* plist)
{
	LTNode* cur = plist->next;
	while (cur != plist)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
}

void LTPushBack(LTNode* plist, LTDataType x)
{
	assert(plist);
	LTNode* tail = plist->prev;
	LTNode* newnode = CreateLTNode(x);
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = plist;
	plist->prev = newnode;

}

void LTPushFront(LTNode* plist, LTDataType x)
{
	assert(plist);
	LTNode* next = plist->next;
	LTNode* newnode = CreateLTNode(x);
	plist->next = newnode;
	newnode->prev = plist;
	newnode->next = next;
	next->prev = newnode;
}

void LTPopBack(LTNode* plist)
{
	assert(plist);
	assert(plist->next != plist);
	LTNode* tail = plist->prev;
	LTNode* prev = tail->prev;
	prev->next = plist;
	plist->prev = prev;
	free(tail);
	tail = NULL;
}

void LTPopFront(LTNode* plist)
{
	assert(plist);
	assert(plist->next != plist);
	LTNode* front = plist->next;
	LTNode* next = front->next;
	plist->next = next;
	next->prev = plist;
	free(front);
	front = NULL;
}

LTNode* LTFind(LTNode* plist, LTDataType x)
{
	assert(plist);
	LTNode* cur = plist->next;
	while (cur != plist)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	
	return NULL;
}

void LTInsert(LTNode* plist, LTNode* pos, LTDataType x)
{
	assert(plist);
	LTNode* prev = pos->prev;
	LTNode* newnode = CreateLTNode(x);
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void LTErase(LTNode* plist, LTNode* pos)
{
	assert(plist);
	assert(plist->next != plist);
	LTNode* prev = pos->prev;
	LTNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
	pos = NULL;
}